package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.AesUtils
import cn.com.kh.HttpClientProxy
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.json.JSONObject

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 * @Title: 外部系统嵌入工单界面API* @author: LiJuntao* @date 2021-07-13 23:58:55
 *
 */

public class apiDynLogin implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiDynLogin.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        String SECRET_KEY = KHDBConfig.getParam(eliteBean, "USEKEY"); ;
        String DOMAIN = KHDBConfig.getParam(eliteBean, "NGSDOM");

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");

        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);
        String dataSourceID = "dataSource";

        //获取所有参数名
        Enumeration e = request.getParameterNames();
        while (e.hasMoreElements()) {
            //获取当前参数名
            String parameterName = (String) e.nextElement();
            //再通过request.getParameter("")的方法来获取对应参数名的值
            log.debug(parameterName + ": " + request.getParameter(parameterName));
        }

        // 获取嵌入传递的参数
        String openid = request.getParameter("openid");
        String cuserid = request.getParameter("cuserid");
        String dynid = request.getParameter("dynid");
        String woid = request.getParameter("woid");
        String taskid = request.getParameter("taskid");
        String opsource = request.getParameter("opsource");
        String type = request.getParameter("type");

        /*
        // 非空校验检查检查
        if (opsource!='zjj'&&(KHUtil.isNull(openid) && KHUtil.isNull(cuserid)) || KHUtil.isNull(dynid)) {
            return "登录信息异常";
        } else {
         */
        if (opsource == 'minip' && !KHUtil.isNull(dynid) && (!KHUtil.isNull(openid) || !KHUtil.isNull(cuserid))) {
            // 预定义返回用户信息
            String userid = "";
            String usertype = "";
            if (!KHUtil.isNull(cuserid)) {

                // 处理用户ID加密信息
                AesUtils aesutil = new AesUtils();
                log.debug("解密前：" + cuserid);
                cuserid = aesutil.aesDecrypt(cuserid, SECRET_KEY);
                log.debug("解密后：" + cuserid);

                // 通过用户ID查询当前系统是否已经存在客户
                List selectExits = eliteBean.chaxun_sql("select customer_guid as userid, loginname, 'customer' as usertype, 2 as sno from customer where customer_id = '" + cuserid + "'  order by sno limit 1", dataSourceID);

                log.debug("通过用户ID查询当前系统是否已经存在客户:" + selectExits.toString());

                if (selectExits.size() > 0) {
                    Map selectExitsm = selectExits.get(0);
                    userid = selectExitsm.get("userid");
                    usertype = selectExitsm.get("usertype");

                    JSONObject customerJson = getCustomerInfo(eliteBean, cuserid);

                    if (!KHUtil.isNull(customerJson.toString())) {

                        String customerName = KHUtil.GetJV(customerJson, "customerName");// 客户姓名
                        String idCard = KHUtil.GetJV(customerJson, "idCard");// 身份证号
                        String mobile = KHUtil.GetJV(customerJson, "mobile");// 手机号码
                        String sex = KHUtil.GetJV(customerJson, "sex");// 性别
                        String id = KHUtil.GetJV(customerJson, "id");// 客户编号

                        // 更新客户信息
                        String updateCustSQL = "update customer set Customer_id = '" + id + "', Customername = '" + customerName + "', Mobile = '" + mobile + "', Customerid = '" + idCard + "', Gender ='" + sex + "', Parent_Guid = '" + id + "',  " +
                                "Wechatid = case when '" + openid + "' != '' then '" + openid + "' else Wechatid end,MODIFIEDBY = 'SELITE',MODIFIEDDATE = NOW() where customer_guid = '" + userid + "'";

                        def row = eliteBean.update(updateCustSQL, dataSourceID);
                        log.debug("客户信息已经更新完成:" + row);
                    }

                } else {
                    JSONObject customerJson = getCustomerInfo(eliteBean, cuserid);

                    if (!KHUtil.isNull(customerJson.toString())) {

                        String customerName = KHUtil.GetJV(customerJson, "customerName");// 客户姓名
                        String idCard = KHUtil.GetJV(customerJson, "idCard");// 身份证号
                        String mobile = KHUtil.GetJV(customerJson, "mobile");// 手机号码
                        String sex = KHUtil.GetJV(customerJson, "sex");// 性别
                        String id = KHUtil.GetJV(customerJson, "id");// 客户编号

                        // 更新客户信息
                        String Customer_Guid = "API_" + KHUtil.getRandomString(32).toUpperCase();
                        String Loginname = KHUtil.getRandomString(6).toUpperCase();
                        String insertSql1 = "Insert Into Customer (Customer_Guid, Customer_id, Customername, Mobile, Customerid, Gender, Parent_Guid, Loginname, Wechatid, CREATEDBY, CREATEDDATE, DATATYPE) Values" +
                                " ('" + Customer_Guid + "', '" + id + "', '" + customerName + "', '" + mobile + "', '" + idCard + "', '" + sex + "', '" + id + "', '" + Loginname + "', '" + openid + "','SELITE',Now(),'API')";
                        def row = eliteBean.update(insertSql1, dataSourceID);
                        log.debug("客户信息已经新建完成:" + row);

                        userid = Customer_Guid;
                        usertype = "customer";
                        log.info("新增customer编号为:" + userid + "|" + row);

                    } else {

                        if (!KHUtil.isNull(openid)) {
                            userid = openid;
                            usertype = "notype";

                        } else {

                            return "登录信息异常";
                        }

                    }

                }

            } else {


                // 通过微信ID查询当前系统是否已经存在客户
                List selectExits = eliteBean.chaxun_sql("select customer_guid as userid, loginname, 'customer' as usertype, 2 as sno from customer where Wechatid = '" + openid + "' order by sno limit 1", dataSourceID);
                log.debug("通过微信ID查询当前系统是否已经存在客户:" + selectExits.toString());

                if (selectExits.size() > 0) {

                    Map selectExitsm = selectExits.get(0);
                    userid = selectExitsm.get("userid");
                    usertype = selectExitsm.get("usertype");
                } else {

                    userid = openid;
                    usertype = "notype";

                }

            }
            log.debug("获取当前登录人在系统中的信息:" + userid + "/" + usertype);

            //获取NGS菜单短码
            String apiLinkJson = Util.doHttpGet(DOMAIN + "/ngsapitask/api/apiShortenLink?dynid=" + dynid + "&userid=" + userid + "&usertype=" + usertype + "&woid=" + woid + "&taskid=" + taskid + "&expand=&cbtype=&opsource=" + opsource, "UTF-8",
                    5000, 0);
            JSONObject reLinkJson = new JSONObject(apiLinkJson);
            log.debug("获取的短链接地址:" + reLinkJson.toString());
            String linkURL = KHUtil.GetJV(reLinkJson, "message");

            response.sendRedirect(linkURL);

        } else if (opsource == 'zjj') {
            log.debug("自助机访问入口:" + type);

            if (type == 'ywbl') {
                dynid = 'DPX8RF';
            } else if (type == 'khts') {
                dynid = 'CKW2WP';
            }

            String apiLinkJson = Util.doHttpGet(DOMAIN + "/ngsapitask/api/apiShortenLink?dynid=" + dynid + "&userid=1" + "&usertype=notype" + "&woid=" + woid + "&taskid=" + taskid + "&expand=&cbtype=&opsource=" + opsource + "&type=" + type, "UTF-8",
                    5000, 0);
            JSONObject reLinkJson = new JSONObject(apiLinkJson);
            log.debug("获取的短链接地址:" + reLinkJson.toString());
            String linkURL = KHUtil.GetJV(reLinkJson, "message");

            response.sendRedirect(linkURL);
        } else {
            return "登录信息异常";
        }

    }

    /**
     * 调用用户信息接口获取用户信息
     */
    public static JSONObject getCustomerInfo(EliteBean eliteBean, String cuserid) {

        JSONObject customerInfo = new JSONObject();
        def httpURL = KHDBConfig.getAPIURL(eliteBean, "findCustomerInfo");

        def result = HttpClientProxy.sendPost(httpURL + "?id=" + cuserid, "", "", 0);
        log.info("[获取客户查询结果]:" + result);

        JSONObject re_json = new JSONObject(result);
        String re_status = KHUtil.GetJV(re_json, "status");
        if (re_status == "200" && !KHUtil.isNull(KHUtil.GetJV(re_json, "data"))) {

            customerInfo = new JSONObject(KHUtil.GetJV(re_json, "data"));

        }

        log.debug("[返回的用户信息Json]:" + customerInfo.toString());

        return customerInfo;

    }

}